<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 修改设备
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>

      <Form :model="bloc.deviceId" label-position="right" :label-width="100" :rules="ruleValidate"
            ref="formValidateEdit" required>
        <FormItem label="设备分类:" prop="sortId" style="text-align: left" required>
                    <span>
                      </span>
          <Select v-model="bloc.deviceId.sortId" @on-change="handleChange(bloc.deviceId.sortId)"
                  style="width: 400px;height: 40px;">
            <Option
              v-for="(item,index) in bloc.sortList"
              :value="item.id"
              :key="index"
            >{{ item.sortName }}
            </Option>
          </Select>
        </FormItem>

        <FormItem label="设备型号:" prop="modelId" style="text-align: left" required>
          <Select v-model="bloc.deviceId.modelId" style="width: 400px;height: 40px;">
            <Option
              v-for="item in bloc.modelList"
              :value="item.id"
              :key="item.id"
            >{{ item.modelName }}
            </Option>
          </Select>
        </FormItem>

        <FormItem label="设备ID:" prop="deviceSn" required>
          <Input v-model="bloc.deviceId.deviceSn" style="width: 400px;height: 40px;"></Input>
        </FormItem>
        <!-- <FormItem label="启动页开关:" prop="startSwitch">
          <i-switch v-model="bloc.deviceId.startSwitch" size="large" style="margin-top: 10px;">
                <template #open>
                  <span>开</span>
                </template>
                <template #close>
                  <span>关</span>
                </template>
            </i-switch>
        </FormItem>
        <FormItem label="显示时间:" prop="startTime">
          <Input v-model="bloc.deviceId.startTime" style="width: 400px;height: 40px;" placeholder="默认5s"></Input>
        </FormItem> -->
        <!-- <FormItem label="启动页类型:" prop="startType" style="text-align: left">
          <Select v-model="bloc.deviceId.startType" style="width: 400px;height: 40px;">
            <Option
              :value="1"
              :key="1"
            >文字
            </Option>
            <Option
              :value="2"
              :key="2"
            >图片
            </Option>
            <Option
              :value="3"
              :key="3"
            >视频
            </Option>
          </Select>
        </FormItem> -->
        <FormItem label="文字:" prop="startImage" v-if="bloc.deviceId.startType===1">
          <Input v-model="bloc.deviceId.startImage" style="width: 400px;height: 40px;"></Input>
        </FormItem>
        <FormItem label="图片:" prop="startImage">
          <div class="demo-upload-list" v-if="bloc.deviceId.startImage.length">
            <template>
              <img :src="bloc.deviceId.startImage">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView()"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(bloc.deviceId.startImage)"></Icon>
              </div>
            </template>
<!--             <template v-else>-->
<!--              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>-->
<!--            </template>-->
          </div>
          <Upload
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="5000"
            :format="['jpg','png']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-success="handleSuccess"
            type="drag"
            style="display: inline-block;width:58px;margin-left:15px"
          >
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View File" v-model="visible">
              <img :src="fileUrl" v-if="visible&&fileType===1" style="width: 100%" />
              <!-- <video controls :src="fileUrl" v-if="visible&&fileType==2" style="width: 100%" /> -->
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持 JPG、PNG格式</p>
        </FormItem>
        <FormItem label="视频:" prop="startImage" v-if="bloc.deviceId.startType===3">
          <div class="demo-upload-list" v-if="bloc.deviceId.startImage.length>0">
            <template>
              <video :src="bloc.deviceId.startImage"></video>
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView()"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(bloc.deviceId.startImage)"></Icon>
              </div>
            </template>
            <!-- <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template> -->
          </div>
          <Upload
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="5000"
            :format="['mp4']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-success="handleSuccess"
            type="drag"
            style="display: inline-block;width:58px;margin-left:15px"
          >
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View File" v-model="visible">
              <img :src="fileUrl" v-if="visible&&fileType===1" style="width: 100%" />
              <video controls :src="fileUrl" v-if="visible&&fileType===2" style="width: 100%" />
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持MP4格式</p>
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px;">
        <Button style="width: 100px;height: 40px;" @click="handleCancel()">返回</Button>
        <Button
          style="margin-left: 30px;width: 100px;height: 40px;"
          type="primary"
          :loading="btnload.loading"
          @click="handleSubmit('formValidateEdit')"
        >保存
        </Button>
      </div>
    </Card>
  </div>
</template>

<script lang="ts">
  import {Component, Vue} from 'vue-property-decorator';
  import {Route} from 'vue-router';
  import {DevicesBloc} from './DevicesBloc';
  import CompanySeletorSingle from '@/component/CompanySeletorSingle.vue';
  import {Loading} from '@/base/Loading';
  import {store} from '@/store/Store';
  import {baseUrl} from '@/base/Request';

  @Component({
    components: {CompanySeletorSingle}
  })

  export default class extends Vue {
    disabled: boolean = true

    beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
      next(vm => {
        vm.bloc.toModifyItem(vm.idx)
          .then(res => {
            vm.bloc.getModel(Number(res.modelId))
              .then(res => {
                vm.bloc.modelList = [{id: res.data.id, modelName: res.data.modelName}]
              })
          })
        vm.bloc.getAllSort(1, 1000, 'ASC')
      });
    }

    bloc = new DevicesBloc()
    btnload = new Loading()

    get uploadHeaders() {
      return {
        'Authorization': 'Bearer ' + store.state.auth.accessToken
      }
    };

    get uploadAction() {
      return `${baseUrl}/api/upload/image`
    }

    fileUrl = '';
    // 1图片  2视频
    fileType = 1 ;
    visible = false;

    get fileList() {
      return this.bloc.fileList.map(x => {
        return {'name': 'name', 'modelIcon': x, 'status': 'finished'};
      });
    }
    handleMaxSize(file) {
      // this.$Notice.warning({
      //   title: '超出了文件大小限制',
      //   desc: file.name + ' 文件太大，不能超出2M'
      // });
      this.$Message.error('图片大小不能超过5M')
    }

    handleFormatError(file) {
      // this.$Notice.warning({
      //   title: '文件格式不正确',
      //   desc: file.name + '文件格式不正确，请选择格式为 JPG、PNG格式的文件'
      // });
      this.$Message.error('请选择格式为JPG、PNG格式的文件，小于5M，建议尺寸')
    }

    handleSuccess(res, file) {
      this.bloc.deviceId.startImage = res.data[0]
      if (res.data[0].indexOf('mp4') > -1) {
        this.fileType = 2;
      }
      // if (this.bloc.fileList.length > 0) {
      //   this.bloc.fileList = []
      // }
      // this.bloc.fileList.push(this.bloc.deviceId.startImage)
    }
    handleRemove(res) {
      this.bloc.deviceId.startImage = '';
    }
    get idx() {
      return Number(this.$route.params.id);
    }

    $refs!: {
      formValidateEdit: HTMLFormElement,
    };
    ruleValidate: any = {
      modelId: [
        {required: true, message: '设备型号不能为空', trigger: 'change', type: 'number'}
      ],
      sortId: [
        {required: true, message: '设备分类不能为空', trigger: 'change', type: 'number'}
      ],
      deviceSn: [
        {required: true, message: '设备ID不能为空', trigger: 'blur'}
      ]
    };

    handleView() {
      this.fileUrl = this.bloc.deviceId.startImage;
      this.visible = true;
    }

    handleChange(sortId) {
      this.bloc
        .getAllModel(this.bloc.angent.pageIndex, 1000, sortId, 'DESC', undefined)
        .then(res => {
        })
        .finally(() => {
          this.bloc
            .getAllSort(this.bloc.angent.pageIndex, 1000, 'ASC');
        });
    }

    handleCancel() {
      this.$router.push({path: '/device-manage/devices'})
    }

    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.bloc.modifyItem(this.bloc.deviceId.id, this.bloc.deviceId.deviceSn)
            .then(res => {
              this.$Message.success('修改设备成功!');
              this.$router.push({path: '/device-manage/devices'})
            })
            .catch(err => {
              this.$Message.error(err.message)
            })
          ;
        }
      });
    }

  }
</script>

<style lang="less" scoped>
  /deep/ .ivu-form-item-content {
    display: flex !important;
    justify-content: start !important;
    align-items: center !important;
  }
</style>
